#include <stdio.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <string.h>
#include <netinet/in.h>

#define N 128

int main(int argc,char const *argv[])//需要传入参数运行
{
        if(argc<3)
	{
		fprintf(stderr,"Usage: %s ip port\n",argv[0]);
		exit(1);
	}

	//1.创建套接字
	int sockfd;
	if((sockfd = socket(AF_INET,SOCK_DGRAM,0))==-1)
	{
		perror("fail to socket\n");
		exit(1);
	}

    printf("sockfd = %d\n",sockfd);

	//2.服务器地址信息结构体
	struct sockaddr_in serveraddr;
	socklen_t addrlen = sizeof(serveraddr);
	serveraddr.sin_family = AF_INET;
	serveraddr.sin_addr.s_addr = inet_addr(argv[1]);
	serveraddr.sin_port = htons(atoi(argv[2]));


      

	//3.发送数据
	char buf[N] ="";
	while(1)
	{
		fgets(buf,N,stdin);
		buf[strlen(buf)-1]=='\0';
		if(sendto(sockfd,buf,N,0,(struct sockaddr *)&serveraddr,addrlen)==-1)
		{
            perror("fail to sendto\n");
		    exit(1);
		}
        
		char buf[N]="";
		 if(recvfrom(sockfd,buf,sizeof(buf),0,(struct sockaddr *)&serveraddr,&addrlen)<0)
		{
            perror("fail to recvfrom\n");
		    exit(1);
		} 
		printf("%s\n",buf);
	}

    //4.关闭套接字
	close(sockfd);
	return 0;
}